package com.ruoyi.web.controller.dating;

import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.DatingMember;
import com.ruoyi.system.domain.SysRegion;
import com.ruoyi.system.domain.vo.*;
import com.ruoyi.system.service.ISysRegionService;
import com.ruoyi.system.service.IDatingMemberService;

/**
 * 婚恋人员信息Controller
 * 
 * @author ruoyi
 * @date 2024-01-15
 */
@RestController
@RequestMapping("/dating/member")
public class DatingMemberController extends BaseController
{
    private static final Logger logger = LoggerFactory.getLogger(DatingMemberController.class);

    @Autowired
    private IDatingMemberService datingMemberService;

    @Autowired
    private ISysRegionService sysRegionService;

    /**
     * 查询婚恋人员信息列表
     */
    @PreAuthorize("@ss.hasPermi('dating:member:list')")
    @GetMapping("/list")
    public TableDataInfo list(DatingMember datingMember)
    {
        startPage();
        List<DatingMember> list = datingMemberService.selectDatingMemberList(datingMember);
        return getDataTable(list);
    }

    /**
     * 导出婚恋人员信息列表
     */
    @PreAuthorize("@ss.hasPermi('dating:member:export')")
    @Log(title = "婚恋人员信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, DatingMember datingMember)
    {
        List<DatingMember> list = datingMemberService.selectDatingMemberList(datingMember);
        ExcelUtil<DatingMember> util = new ExcelUtil<DatingMember>(DatingMember.class);
        util.exportExcel(response, list, "婚恋人员信息数据");
    }

    /**
     * 获取婚恋人员信息详细信息
     */
    @PreAuthorize("@ss.hasPermi('dating:member:query')")
    @GetMapping(value = "/{memberId}")
    public AjaxResult getInfo(@PathVariable("memberId") Long memberId)
    {
        DatingMember member = datingMemberService.selectDatingMemberByMemberId(memberId);
        if (member != null) {
            // 构造regionIds数组用于前端回显
            buildRegionIdsForResponse(member);
        }
        return success(member);
    }

    /**
     * 新增婚恋人员信息
     */
    @PreAuthorize("@ss.hasPermi('dating:member:add')")
    @Log(title = "婚恋人员信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody DatingMember datingMember)
    {
        // 处理地区ID转换为地区名称
        processRegionIds(datingMember);
        return toAjax(datingMemberService.insertDatingMember(datingMember));
    }

    /**
     * 修改婚恋人员信息
     */
    @PreAuthorize("@ss.hasPermi('dating:member:edit')")
    @Log(title = "婚恋人员信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody DatingMember datingMember)
    {
        // 处理地区ID转换为地区名称
        processRegionIds(datingMember);
        return toAjax(datingMemberService.updateDatingMember(datingMember));
    }

    /**
     * 删除婚恋人员信息
     */
    @PreAuthorize("@ss.hasPermi('dating:member:remove')")
    @Log(title = "婚恋人员信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{memberIds}")
    public AjaxResult remove(@PathVariable Long[] memberIds)
    {
        return toAjax(datingMemberService.deleteDatingMemberByMemberIds(memberIds));
    }

    /**
     * 校验人员编号是否唯一
     */
    @GetMapping("/checkMemberNoUnique")
    public AjaxResult checkMemberNoUnique(DatingMember datingMember)
    {
        return success(datingMemberService.checkMemberNoUnique(datingMember));
    }

    /**
     * 校验手机号码是否唯一
     */
    @GetMapping("/checkPhoneUnique")
    public AjaxResult checkPhoneUnique(DatingMember datingMember)
    {
        return success(datingMemberService.checkPhoneUnique(datingMember));
    }

    /**
     * 获取婚恋人员信息导入模板
     */
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response)
    {
        ExcelUtil<DatingMember> util = new ExcelUtil<DatingMember>(DatingMember.class);
        util.importTemplateExcel(response, "婚恋人员信息数据");
    }

    /**
     * 导入婚恋人员信息
     */
    @PreAuthorize("@ss.hasPermi('dating:member:import')")
    @Log(title = "婚恋人员信息", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        ExcelUtil<DatingMember> util = new ExcelUtil<DatingMember>(DatingMember.class);
        List<DatingMember> memberList = util.importExcel(file.getInputStream());
        String operName = getUsername();
        String message = datingMemberService.importMember(memberList, updateSupport, operName);
        return success(message);
    }

    /**
     * 获取婚恋平台统计数据
     */
    @PreAuthorize("@ss.hasPermi('dating:member:list')")
    @GetMapping("/statistics")
    public AjaxResult getStatistics()
    {
        DatingStatisticsVO statistics = datingMemberService.getStatistics();
        return success(statistics);
    }

    /**
     * 获取每日人员增长统计
     */
    @PreAuthorize("@ss.hasPermi('dating:member:list')")
    @GetMapping("/dailyGrowth")
    public AjaxResult getDailyGrowth(Integer days)
    {
        if (days == null || days <= 0) {
            days = 30; // 默认30天
        }
        DatingGrowthVO growthData = datingMemberService.getDailyGrowth(days);
        return success(growthData);
    }

    /**
     * 获取性别分布统计
     */
    @PreAuthorize("@ss.hasPermi('dating:member:list')")
    @GetMapping("/genderDistribution")
    public AjaxResult getGenderDistribution()
    {
        DatingGenderVO genderData = datingMemberService.getGenderDistribution();
        return success(genderData);
    }

    /**
     * 获取年龄分布统计
     */
    @PreAuthorize("@ss.hasPermi('dating:member:list')")
    @GetMapping("/ageDistribution")
    public AjaxResult getAgeDistribution()
    {
        DatingAgeVO ageData = datingMemberService.getAgeDistribution();
        return success(ageData);
    }

    /**
     * 获取收入分布统计
     */
    @PreAuthorize("@ss.hasPermi('dating:member:list')")
    @GetMapping("/incomeDistribution")
    public AjaxResult getIncomeDistribution()
    {
        DatingIncomeVO incomeData = datingMemberService.getIncomeDistribution();
        return success(incomeData);
    }

    /**
     * 处理地区ID数组，转换为地区名称
     * @param datingMember 婚恋人员信息
     */
    private void processRegionIds(DatingMember datingMember) {
        Long[] regionIds = datingMember.getRegionIds();
        if (regionIds != null && regionIds.length > 0) {
            try {
                // 获取省份名称和ID
                if (regionIds.length >= 1 && regionIds[0] != null) {
                    SysRegion province = sysRegionService.selectSysRegionByRegionId(regionIds[0]);
                    if (province != null) {
                        datingMember.setProvince(province.getRegionName());
                        datingMember.setProvinceId(province.getRegionId());
                    }
                }
                
                // 获取城市名称和ID
                if (regionIds.length >= 2 && regionIds[1] != null) {
                    SysRegion city = sysRegionService.selectSysRegionByRegionId(regionIds[1]);
                    if (city != null) {
                        datingMember.setCity(city.getRegionName());
                        datingMember.setCityId(city.getRegionId());
                    }
                }
                
                // 获取区县名称和ID
                if (regionIds.length >= 3 && regionIds[2] != null) {
                    SysRegion district = sysRegionService.selectSysRegionByRegionId(regionIds[2]);
                    if (district != null) {
                        datingMember.setDistrict(district.getRegionName());
                        datingMember.setDistrictId(district.getRegionId());
                    }
                }
            } catch (Exception e) {
                // 记录日志，不影响主要流程
                logger.error("转换地区ID为地区名称时发生错误: {}", e.getMessage(), e);
            }
        }
    }

    /**
     * 构造regionIds数组用于前端回显
     * @param datingMember 婚恋人员信息
     */
    private void buildRegionIdsForResponse(DatingMember datingMember) {
        java.util.List<Long> regionIdsList = new java.util.ArrayList<>();
        
        if (datingMember.getProvinceId() != null) {
            regionIdsList.add(datingMember.getProvinceId());
        }
        if (datingMember.getCityId() != null) {
            regionIdsList.add(datingMember.getCityId());
        }
        if (datingMember.getDistrictId() != null) {
            regionIdsList.add(datingMember.getDistrictId());
        }
        
        if (!regionIdsList.isEmpty()) {
            Long[] regionIds = regionIdsList.toArray(new Long[0]);
            datingMember.setRegionIds(regionIds);
        }
    }
} 